var express = require('express');
var router = express.Router();
var multiparty = require("multiparty");
var path = require('path');
var fs = require("fs");
var sprite_application = require('../child_application/spritesmith/index');
const { exec, execFile, execSync, spawn, fork } = require('child_process');



const Command = {
    defaultNameSpace: 'sprite',
    /**
     * 上传图片
     * @param {*} req 
     * @param {*} res 
     * @param {*} next 
     * @param {string} namespace 图片储存的文件夹名字
     */
    upload(req, res, next, namespace = this.defaultNameSpace) {
        var command = this;
        var uploadDir = path.resolve(__dirname, '../public/sprite_images', namespace)
        fs.exists(uploadDir, function (exists) {
            if (exists) {
                // 文件存在
                var folder_exists = fs.existsSync(uploadDir);
                if (folder_exists == true) {
                    var dirList = fs.readdirSync(uploadDir);
                    dirList.forEach(function (fileName) {
                        console.log('------->删除：', path.resolve(uploadDir, fileName))
                        fs.unlinkSync(path.resolve(uploadDir, fileName));
                    });
                }
                command._upload(req, res, next, { uploadDir });
            }
            if (!exists) {
                // 文件不存在
                fs.mkdir(uploadDir, function (err) {
                    if (err) {
                        res.json({
                            success: false,
                            msg: err.message
                        });
                    }
                    else {
                        console.log('------->创建：', uploadDir)
                        command._upload(req, res, next, { uploadDir });
                    }
                });
            }
        })

    },
    _upload(req, res, next, options = {}) {
        var form = new multiparty.Form(options);
        form.parse(req, function (err, fields, files) {
            // console.log(fields, files,' fields2')
            if (err) {
                res.json({
                    success: false,
                    msg: err.message
                })
            } else {
                sprite_application.entry({
                    src_cwd: options.uploadDir
                }, function (err,data) {
                    if (err) {
                        res.json({
                            success: false,
                            msg: err.message || '构建出错'
                        })
                    }
                    else {
                        res.json({
                            success: true,
                            msg: '上传成功',
                            data: {
                                uploadedFiles: Object.keys(files),
                                options:JSON.stringify(data)
                            }
                        })
                    }
                })
                // var cp = fork(path.resolve(__dirname, '../child_application/spritesmith/index.js'), [`src_cwd=${options.uploadDir}`]);
                // cp.on('close', function (code) {
                //     console.log('子进程已退出，退出码 ' + code);
                // });
                // let _process = exec(`node ${path.resolve(__dirname, '../child_application/spritesmith/index.js')} src_cwd=${options.uploadDir}`, {});
                // _process.stdout.on('data', function (data) {
                //     console.log('stdout: ' + data);
                //     res.json({
                //         success: true,
                //         msg: '上传成功',
                //         data: {
                //             uploadedFiles: Object.keys(files)
                //         }
                //     })
                // });

                // _process.stderr.on('data', function (data) {
                //     console.log('stderr: ' + data);
                // });
                // _process.on('exit',(code) =>{
                //     console.log('exit: ' + code);
                // })
                // _process.on('close',(code) =>{
                //     console.log('close: ' + code);
                // })

            }
        });
    }
}



/* GET users listing. */
router.get('/', function (req, res, next) {
    res.render('sprite');
});
router.post('/', function (req, res, next) {
    if (JSON.stringify(req.query) !== '{}') {
        switch (req.query.command) {
            case 'upload':
                let namespace = req.query.namespace || Command.defaultNameSpace;
                Command.upload(req, res, next, namespace);
                break;
            default:
                res.json({
                    success: false,
                    msg: '缺少查询参数'
                });
                break;
        }
    }
    else {
        res.json({
            success: false,
            msg: '缺少查询参数'
        });
    }
});





module.exports = router;